import time

from flask import Blueprint, g, request, jsonify, current_app

from config import DevelopmentConfig
import redis

from decorators import login_required
from models import RatingsModel, StreamUserRecsModel, ProductModel

bp = Blueprint("online", __name__, url_prefix="/online")


@bp.route("/rating_redis", methods=['POST'])
@login_required
def redis_message_product():
    # 获取数据
    data = request.get_json()
    product_id = data.get("product_id")
    rating = data.get("rating")
    # 连接到 Redis 服务器
    redis_client = redis.StrictRedis(host=DevelopmentConfig.redis_host, port=DevelopmentConfig.redis_port)
    # noinspection LongLine
    rating_data = RatingsModel.query.filter_by(user_id=g.user.user_id).order_by(RatingsModel.rating_time.desc()).limit(
        5).all()
    # 构建包含PRODUCTID:SCORE的列表
    product_score_list = [f"{record.product_id}:{record.rating}" for record in rating_data]
    product_score_list.append(f"{product_id}:{rating}")
    # 构建键名
    redis_key = f'userId:{g.user.user_id}'
    try:
        # 发送数据
        redis_client.lpush(redis_key, *product_score_list)
        # 创建 Pipeline 对象
        pipeline = redis_client.pipeline()
        # 执行 Pipeline 中的所有请求
        pipeline.execute()
        return jsonify({"status": "success"})
    except Exception as e:
        return jsonify({"status": "fail", "message": e})


@bp.route("/rating_log", methods=['POST', "GET"])
@login_required
def rating_log():
    # 获取数据
    data = request.get_json()
    product_id = data.get("product_id")
    rating = data.get("rating")

    # 添加日志前缀
    log_message = f'PRODUCT_RATING_PREFIX:{g.user.user_id}|{product_id}|{rating}|{int(time.time())}'

    current_app.logger.info(log_message)

    return jsonify({"status": "success"})


@bp.route("/onlineRecs")
@login_required
def onlineRecs():
    recs = StreamUserRecsModel.query.filter_by(user_id=g.user.user_id).first()
    productIdList = [x["product_id"] for x in recs.recommendations]
    # 查询商品信息
    productsList = ProductModel.query.filter(ProductModel.product_id.in_(productIdList)).all()
    # 转字典之后json
    productsList = [{k: v for k, v in product.__dict__.items() if k != '_sa_instance_state'} for product in
                    productsList]
    return jsonify({"productsList": productsList})
